'use strict';
import React from "react";
import { View, StyleSheet, ScrollView, Text, TouchableOpacityComponent, TouchableOpacity } from "react-native";
import Container from "../../component/common/Container";
import NavigationBar from "../../component/navigation/NavigationBar";
import VideoPlayer from '../../component/video/index'
import Orientation from "react-native-orientation";
import ImageView from "../../component/common/ImageView";
import Button from "../../component/common/Button";
import { inject, observer } from "mobx-react";
import CommentView from "../../component/common/CommentView";

@inject('loginStore','taskStore')
@observer
class VideoDetail extends React.Component {

    constructor(props) {
        super(props);
        const { params } = this.props.navigation.state;
        this.information_id = params['information_id'];
        // console.log('视频详情传过来的id', this.information_id);
        this.state = { data: { videoVOs: [{}] } }
    }

    componentDidMount() {
        //完成初始化
        Orientation.addOrientationListener(this._orientationDidChange);
        this.requestVideoDetail();
    }

    componentWillUnmount() {
        Orientation.removeOrientationListener(this._orientationDidChange);
    }

    _orientationDidChange = (orientation) => {
        if (orientation === 'LANDSCAPE') {
            this.setState({ navHidden: true })
        } else {
            this.setState({ navHidden: false })
        }
    };

    _onPressBack = () => {
        RouterHelper.goBack();
    };

    requestVideoDetail = async () => {
        const result = await Services.post(ServicesApi.INFORMATION_DETAIL, { information_id: this.information_id, focus_user: global.secretKey });
        // console.log('视频详情返回----------->', result);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({ data: result.data });
            // console.log(`${ServicesApi.QI_NIU_LINK}${this.state.data.videoVOs[0].video_url}`);
            this._readTimes();
        } else {
            ToastManager.show(result.dec || 'error');
        }
    };

    //记录阅读次数
    _readTimes = async () => {
        const {taskStore} = this.props;
        const saveRes = await taskStore.saveTask('reading');
        // console.log('视频详情保存任务------------>',saveRes);
    };

    _onPressWatch = async () => {
        const { loginStore } = this.props;
        const { data } = this.state;
        let url;
        let params;
        if (data.focus_state !== '0') { //已经关注，点击取关
            url = ServicesApi.FOCUS_DEL;
            params = {
                focus_user: global.secretKey,
                focus_by_user: data.author_id,
                type: 'field',
            }
        } else { //还没关注，点击关注
            url = ServicesApi.FOCUS_SAVE;
            params = {
                focus_user: global.secretKey,
                focus_by_user: data.author_id,
            }
        }
        const result = await Services.post(url, params);
        // console.log('关注/取关返回------------>', result);
        if (result.code === StatusCode.SUCCESS_CODE) {
            let temp = { ...data };
            if (data.focus_state !== '0') { //取关
                temp.focus_state = '0';
                ToastManager.show('取消关注成功!')
            } else { //关注
                temp.focus_state = '1';
                ToastManager.show('关注成功!')
            }
            this.setState({ data: temp });
            await loginStore.getUserData(global.secretKey);
        } else {
            ToastManager.show(result.dec || 'error');
        }
    };

    _onPressUserCenter = () => {
        RouterHelper.navigate('', 'UserCenter', { author_id: this.state.data.author_id })
    };

    render() {
        const width = SCREEN_WIDTH;
        const height = width * 0.568;
        const { data } = this.state;
        let videoUrl;
        if (Array.isArray(data.videoVOs) && data.videoVOs.length !== 0) {
            videoUrl = data.data_type === 'local' ? `${ServicesApi.QI_NIU_LINK}${data.videoVOs[0].video_url}` : `${data.videoVOs[0].video_url}`;
        } else {
            videoUrl = null;
        }
        // console.log('videoUrl---->', videoUrl);
        // console.log('data', data, videoUrl, videoUrl !== 'undefined');
        return (
            <Container style={styles.cont}>
                <NavigationBar
                    style={Theme.transparentNavBar}
                    iconStyle={{tintColor: '#fff'}}
                />
                {videoUrl !== 'undefined' ? (
                    <VideoPlayer
                        style={styles.video}
                        videoStyle={{ width, height }}
                        totalDuration={50000}
                        resizeMode={'stretch'}
                        source={{ uri: videoUrl }}
                        showBackButton={false}
                        onPressBack={this._onPressBack}
                    />) : (
                        <View style={[styles.video, { width, height }]} />
                    )}
                <ScrollView style={styles.scroll}>
                    <Text style={styles.videoTitle}>{data.information_title}</Text>
                    <View style={styles.rowView}>
                        <View style={styles.hotView}>
                            <ImageView
                                style={styles.hotImg}
                                source={Images.icon_hot}
                            />
                            <Text style={styles.hotText}>{data.view_counts || 0}</Text>
                        </View>
                        <Text style={styles.hotTime}>{Moment(data.publish_time).format('YYYY-MM-DD HH:mm')}</Text>
                    </View>
                    {data.data_type === 'local' ?
                        <View style={styles.watchView}>
                            <View style={styles.watchInfoView}>
                                <TouchableOpacity onPress={this._onPressUserCenter}>
                                    <ImageView
                                        resizeMode={'cover'}
                                        style={styles.watchIcon}
                                        source={data.user_img ? { uri: data.user_img } : Images.icon_default_avatar}
                                    />
                                </TouchableOpacity>
                                <View style={styles.watchInfoView2}>
                                    <Text style={styles.watchName}>{data.author_name}</Text>
                                    <Text style={styles.watchFansCount}>{`粉丝：${data.followers_count ? data.followers_count : 0}`}</Text>
                                </View>
                            </View>
                            <Button
                                style={styles.watchBtn}
                                titleStyle={styles.watchBtnText}
                                title={data.focus_state !== '0' ? '已关注' : '+ 关注'}
                                onPress={() => this._onPressWatch()}
                            />
                        </View> : null}
                    <Text style={styles.content}>{data.information_content}</Text>
                </ScrollView>
                <CommentView
                    styles={styles.bottomInfo}
                    count={data.topic_counts ? data.topic_counts : 0}
                    topic_id={data.information_id}
                    collect_state={data.collect_state === '0' ? null : data.collect_state}
                    reply_module={'information'}
                    title={data.information_title}
                    article_type={data.article_type}
                    information={data}
                    onCallBack={() => this.requestVideoDetail()}
                />
            </Container>
        );
    }
}

const styles = StyleSheet.create({
    cont: {
        flex: 1,
    },
    video: {
        backgroundColor: '#eee',
        marginTop: -(Theme.statusBarHeight + Theme.navBarHeight),
    },
    scroll: {
        flex: 1,
    },
    videoTitle: {
        marginTop: 8,
        fontSize: FontSize(16),
        color: "#4a4a4a",
        marginHorizontal: 15,
    },
    rowView: {
        flexDirection: 'row',
        marginTop: 10,
        alignItems: 'center',
        justifyContent: 'space-between',
        marginHorizontal: 15,
    },
    hotView: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    hotImg: {
        width: 12,
        height: 14,
    },
    hotText: {
        fontSize: FontSize(13),
        color: "#9d9d9d",
        marginLeft: 5,
    },
    hotTime: {
        fontSize: FontSize(13),
        color: "#9d9d9d",
    },
    watchView: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        backgroundColor: "#f0f0f0",
        marginTop: 15,
        paddingHorizontal: 15,
        paddingVertical: 10,
    },
    watchInfoView: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    watchIcon: {
        width: 41,
        height: 41,
        borderRadius: 41 / 2,
    },
    watchInfoView2: {
        marginLeft: 10,
    },
    watchName: {
        fontSize: FontSize(14),
        color: "#333",
    },
    watchFansCount: {
        marginTop: 2,
        fontSize: FontSize(10),
        color: "#909090",
    },
    watchBtn: {
        borderRadius: 13,
        borderWidth: Theme.minPixel,
        borderColor: "#ffa64f",
        paddingVertical: 6,
        paddingHorizontal: 9,
        backgroundColor: '#fff',
    },
    watchBtnText: {
        fontSize: FontSize(11),
        color: "#ffa64f",
    },
    content: {
        marginHorizontal: 15,
        marginTop: 11,
        fontSize: FontSize(14),
        color: "#9d9d9d",
        lineHeight: 20,
        fontFamily: 'PingFangSC-Regular',
    },
    bottomInfo: {
        flexDirection: 'row',
        position: 'absolute',
        left: 15,
        right: 15,
        bottom: 10,
        alignItems: 'center',

    },
});

export default VideoDetail